package cn.hy.preparelesson.module.business;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hy.preparelesson.common.entity.PlLesson;
import cn.hy.preparelesson.common.enums.PrepareLessonTypeEnum;
import cn.hy.preparelesson.common.enums.SchoolSemesterEnum;
import cn.hy.preparelesson.common.exception.MessageException;
import cn.hy.preparelesson.common.params.PageParams;
import cn.hy.preparelesson.common.permission.RequirePermissions;
import cn.hy.preparelesson.common.service.PlCommentService;
import cn.hy.preparelesson.common.service.PlLessonService;
import cn.hy.preparelesson.common.utils.HttpUtils;
import cn.hy.preparelesson.common.utils.UserUtils;
import cn.hy.preparelesson.common.utils.ValidatorUtils;
import cn.hy.preparelesson.common.vo.*;
import cn.hy.preparelesson.module.business.vo.PersonalLessonExportVo;
import cn.hy.preparelesson.module.business.vo.SchoolLessonExportVo;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mysql.jdbc.log.LogFactory;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 备课管理管理Controller
 */
@RequestMapping("/lesson")
@RestController
public class PrePareLessonController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PlLessonService plLessonService;


    /**
     * 分页获取个人备课列表
     * @param schoolId
     * @param pageParams
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @return
     */
    @RequirePermissions("pl:personlesson:list")
    @RequestMapping("/list")
    public Result findPageBy(@RequestParam("schoolToken") String schoolId, PageParams pageParams, String title,
                             Date createStartTime, Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                             BigDecimal distanceYear, String classId) throws TException {
        PageInfo<PlLesson> plLessonListPageInfo = plLessonService.findValidPageV4By(schoolId, pageParams, title, createStartTime, schoolYear, subjectId, term, createEndTime, distanceYear, classId, UserUtils.getUserId());
        return Result.success(plLessonListPageInfo);
    }

    /**
     * 分页获取全校备课列表
     * @param schoolId
     * @param pageParams
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @return
     */
    @RequirePermissions("pl:schoollesson:list")
    @RequestMapping("/schoolLessonList")
    public Result findSchoolLessonPageBy(@RequestParam("schoolToken") String schoolId, PageParams pageParams, String title,
                             Date createStartTime, Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                             BigDecimal distanceYear, String classId) throws TException {
        PageInfo<PlLesson> plLessonListPageInfo = plLessonService.findValidPageV4By(schoolId, pageParams, title, createStartTime, schoolYear, subjectId, term, createEndTime, distanceYear, classId,null);
        return Result.success(plLessonListPageInfo);
    }
    /**
     * 保存或修改
     * @param lessonSaveVo
     * @return
     */
    @RequirePermissions("pl:personlesson:addOrEdit")
    @RequestMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestParam("schoolToken") String schoolId, LessonSaveVo lessonSaveVo) {
        ValidatorUtils.validateEntity(lessonSaveVo);
        PrepareLessonTypeEnum prepareLessonTypeEnum = PrepareLessonTypeEnum.getByCode(lessonSaveVo.getType());
        if (prepareLessonTypeEnum == null) {
            return Result.error("请选择正确的备课类型!");
        }
        String plClassStr = lessonSaveVo.getClassList();
        if (StringUtils.isBlank(plClassStr)) {
            throw  new MessageException("请选择班级信息！");
        }
        List<ClassVo> classVoList;
        try {
            classVoList = JSONObject.parseObject(plClassStr, new TypeReference< List<ClassVo> >(){});
        } catch (Exception e) {
            logger.error("班级参数错误：", e);
            throw new MessageException("班级参数错误！");
        }
        //todo  校验学科年级班级
        if (StringUtils.isBlank(lessonSaveVo.getId())) {
            List<FilePlLessonVo> filePlLessonVoList = new ArrayList<>();
            if(StringUtils.isNotBlank(lessonSaveVo.getAnndexList())) {
                filePlLessonVoList = JSONObject.parseObject(lessonSaveVo.getAnndexList(), new TypeReference<List<FilePlLessonVo>>(){});
            }
            plLessonService.save(schoolId, UserUtils.getUserId(), lessonSaveVo,classVoList, filePlLessonVoList);
        }else {
            plLessonService.update(schoolId, UserUtils.getUserId(), lessonSaveVo, classVoList);
        }
        return Result.success(null);
    }

    /**
     * 获取备课详情
     * @param schoolId
     * @param plLessonId
     * @return
     */
    @RequestMapping("/detail")
    public Result getPlLessonDetail(@RequestParam("schoolToken")String schoolId, @RequestParam String plLessonId) throws TException {
        PlPrepareLessonDetailVo PlPrepareLessonDetail = plLessonService.findVaildPlLessonDetailBySchoolIdAndId(schoolId, plLessonId);
        return Result.success(PlPrepareLessonDetail);
    }

    /**
     * 根据schoolId 用户 查找备课
     * @param schoolId
     * @param createByList
     * @return
     */
    @RequestMapping("/listByAuthor")
    public Result getLessonListByAuthor(@RequestParam("schoolToken")String schoolId,@RequestParam String createByList) {
        List<String> createdIdList= Arrays.asList(createByList.split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
        List<PlLessonIdAndNameVo> plList =  plLessonService.findValidPlLessonListByAuthor(schoolId, createdIdList);
        return Result.success(plList);
    }
    /**
     * 根据schoolId lessonIdList 查找备课
     * @param schoolId
     * @param lessIdString
     * @return
     */
    @RequestMapping("/listByIdList")
    public Result findValidLessonListByIdIn(@RequestParam("schoolToken")String schoolId, @RequestParam String lessIdString) {
        if (StringUtils.isNotBlank(lessIdString)) {
            List<String> lessonIdList = Arrays.asList(lessIdString.split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
            List<PlLesson> plList =  plLessonService.findValidListBySchoolIdAndIdIn(schoolId, lessonIdList);
            return Result.success(plList);
        }
        return Result.success(null);
    }

    /**
     * 删除备课
     * @param schoolId
     * @param lessonId
     * @return
     */
    @RequirePermissions("pl:personlesson:delete")
    @RequestMapping("/delete")
    public Result delete(@RequestParam("schoolToken")String schoolId, @RequestParam String lessonId) {
        plLessonService.softDeleteLesson(schoolId, lessonId, UserUtils.getUserId());
        return Result.success(null);
    }

    /**
     * 导出个人备课
     * @param request
     * @param response
     * @param schoolId
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @throws TException
     */
    @RequirePermissions("pl:personlesson:export")
    @RequestMapping("/exportPerson")
    public void exportPersonalLesson(HttpServletRequest request, HttpServletResponse response,@RequestParam("schoolToken") String schoolId, String title,
                       Date createStartTime, Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                       BigDecimal distanceYear, String classId) throws TException {
        PageParams pageParams = new PageParams();
        pageParams.setPageSize(Integer.MAX_VALUE);
        PageInfo<PlLesson> plLessonListPageInfo = plLessonService.findValidPageBy(schoolId, pageParams, title, createStartTime, schoolYear,
                subjectId, term, createEndTime, distanceYear, classId, UserUtils.getUserId());
        List<PersonalLessonExportVo> exportVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plLessonListPageInfo.getList())) {
            int seq = 1;
            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            for (PlLesson lesson : plLessonListPageInfo.getList()) {
                PersonalLessonExportVo exportVo = new PersonalLessonExportVo();
                exportVo.setSeq(seq ++);
                if (lesson.getSchoolYear() != null && lesson.getTerm() != null ) {
                    String currentTerm = lesson.getTerm().equals(SchoolSemesterEnum.ONE.getCode()) ? "一" : "二";
                    int year = lesson.getSchoolYear()+1;
                    exportVo.setSemester(lesson.getSchoolYear() + "年-" + year + "第" + currentTerm + "学期");
                }
                exportVo.setTitle(lesson.getTitle());

                if (lesson.getType() != null) {
                    exportVo.setType(PrepareLessonTypeEnum.getByCode(lesson.getType()).getMsg());
                }
                exportVo.setGrade(lesson.getGradeName());
                if (StringUtils.isNotBlank(lesson.getClassNameStr())) {
                    List<String> classNameList = new ArrayList<>();

                    for (String tempClassName : lesson.getClassNameStr().split(",") ) {
                        classNameList.add(tempClassName + "班");
                    }
                    exportVo.setClassName(String.join(",", classNameList));
                }
                if (StringUtils.isNotBlank(lesson.getSubjectName())) {
                    exportVo.setSubject(lesson.getSubjectName());
                }
                exportVo.setCrateBy(lesson.getCreateName());
                exportVo.setCreateAt(dateFormat.format(lesson.getCreateAt()));
                exportVoList.add(exportVo);
            }
        }
        Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(null, null, ExcelType.XSSF),
                PersonalLessonExportVo.class, exportVoList);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + HttpUtils.getEncodeFileName(request, "我的备课.xlsx"));
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            sheets.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出全校备课信息
     * @param request
     * @param response
     * @param schoolId
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @throws TException
     */
    @RequirePermissions("pl:schoollesson:export")
    @RequestMapping("/exportSchool")
    public void  exportSchoolLesson(HttpServletRequest request, HttpServletResponse response,@RequestParam("schoolToken") String schoolId, String title,
                                    Date createStartTime, Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                                    BigDecimal distanceYear, String classId) throws TException {
        PageParams pageParams = new PageParams();
        pageParams.setPageSize(Integer.MAX_VALUE);
        PageInfo<PlLesson> plLessonListPageInfo = plLessonService.findValidPageBy(schoolId, pageParams, title, createStartTime, schoolYear,
                subjectId, term, createEndTime, distanceYear, classId,null);
        List<SchoolLessonExportVo> exportVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plLessonListPageInfo.getList())) {
            int seq = 1;
            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            for (PlLesson lesson : plLessonListPageInfo.getList()) {
                SchoolLessonExportVo exportVo = new SchoolLessonExportVo();
                exportVo.setSeq(seq ++);
                if (lesson.getSchoolYear() != null && lesson.getTerm() != null ) {
                    String currentTerm = lesson.getTerm().equals(SchoolSemesterEnum.ONE.getCode()) ? "一" : "二";
                    int year = lesson.getSchoolYear()+1;
                    exportVo.setSemester(lesson.getSchoolYear() + "年-" + year + "第" + currentTerm + "学期");
                }
                exportVo.setTitle(lesson.getTitle());

                if (lesson.getType() != null) {
                    exportVo.setType(PrepareLessonTypeEnum.getByCode(lesson.getType()).getMsg());
                }
                exportVo.setGrade(lesson.getGradeName());
                if (StringUtils.isNotBlank(lesson.getClassNameStr())) {
                    List<String> classNameList = new ArrayList<>();

                    for (String tempClassName : lesson.getClassNameStr().split(",") ) {
                        classNameList.add(tempClassName + "班");
                    }
                    exportVo.setClassName(String.join(",", classNameList));
                }
                if (StringUtils.isNotBlank(lesson.getSubjectName())) {
                    exportVo.setSubject(lesson.getSubjectName());
                }
                exportVo.setCrateBy(lesson.getCreateName());
                exportVo.setCreateAt(dateFormat.format(lesson.getCreateAt()));
                exportVoList.add(exportVo);
            }
        }
        Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(null, null, ExcelType.XSSF),
                SchoolLessonExportVo.class, exportVoList);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + HttpUtils.getEncodeFileName(request, "全校备课.xlsx"));
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            sheets.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
